package flca.mda.api.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class NestedObject {
	private static final TypeUtils tu = new TypeUtils();

	private List<Class<?>> parents = new ArrayList<Class<?>>();
	private List<Field> fields = new ArrayList<Field>();
	private Class<?> nested;
	
	public static NestedObject copy(Field aField, Class<?> currentClass, NestedObject previous) {
		NestedObject result = new NestedObject();
		if (previous != null) {
			result.parents.addAll(previous.parents);
			result.fields.addAll(previous.fields);
		}
		
		result.fields.add(aField);
		result.parents.add(currentClass);
		result.nested = tu.getGenericOrActualType(aField);
		
		return result;
	}

	public Class<?> getRootClass() {
		return (getParents().isEmpty()) ? null : getParents().get(0);
	}
	
	public Class<?> lastParentClass() {
		return (getParents().isEmpty()) ? null : getParents().get(getParents().size()-1);
	}

	public Field lastField() {
		return (getFields().isEmpty()) ? null : getFields().get(getFields().size()-1);
	}
	

 	public List<Class<?>> getParents() {
		return parents;
	}

	public List<Field> getFields() {
		return fields;
	}

	public Class<?> getNested() {
		return nested;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (Class<?> p : parents) {
			sb.append(p.getSimpleName() + ",");
		}
		sb.append("], fields=[");
		for (Field f : fields) {
			sb.append(f.getName() + ",");
		}
		sb.append("], nested=" + nested.getSimpleName());
		return sb.toString();
	}
}